# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Project Name: luffcity study project
File Name: user_data.py
Author: kij
Create Date: 2021/2/19
-------------------------------------------------
"""
import os
import sys
import pickle
import hashlib
from conf.config import BASE_DIR, ROLE_TUPLE
from data.get_data import get_province, set_city
from org.school_data import School, SchoolClass
from src.select_func import get_user, create_obj, select_func, get_org_list, get_school_class_list


# 创建个角色的元类来实现各级子类

class MyRole(type):
	logon_name = ""
	logon_password = ""

	def __init__(self, class_name, class_bases, class_dic):
		super(MyRole, self).__init__(class_name, class_bases, class_dic)

	def __call__(self, *args, **kwargs):
		# 第一件事 先创造一个对象object
		obj = object.__new__(self)
		# 第二件事 初始化obj
		self.__init__(obj, *args, **kwargs)
		# 第三件事 返回obj
		return obj


class CreateRole(object, metaclass=MyRole):
	def __init__(self, user_name, user_password, role):
		self.user_name = user_name
		self.user_password = user_password
		self.role = role

	def select(self, dic_func):
		for item in dic_func:
			print(item, dic_func[item][0])
		choose = input("输入选择:\n")
		if not choose.isdecimal():
			self.select(dic_func)
		if choose in dic_func:
			dic_func[choose][1](self)
			return
		else:
			print("输入有误")
			self.select(dic_func)

	def get_mydata(self):
		"""
		拿到所有存储的数据
		:return:如果存在返回返回类的数据，不存在就返回空
		"""
		file_path = os.path.join(BASE_DIR, "files", "%s.pkl" % self.user_name)
		if not os.path.exists(file_path):
			return None
		else:
			with open(file_path, mode='rb') as user_file:
				while True:
					try:
						user = pickle.load(user_file)
					except EOFError:
						break
			return user

	def save_mydata(self):
		"""
		存储我所有的数据
		:return:
		"""
		file_path = os.path.join(BASE_DIR, "files", "%s.pkl" % self.user_name)
		with open(file_path, mode='ab') as user_file:
			pickle.dump(self, user_file, protocol=2)


class AdminRole(CreateRole):
	"""
	管理者
	"""
	orglist = []

	def __init__(self, user_name, user_password):
		self.user_name = user_name
		self.user_password = user_password
		self.role_name = ROLE_TUPLE[0]

	# 选择机构
	@classmethod
	def select_org(cls, user_name=None):
		org_list = get_org_list(user_name, "org_list.pkl")
		for code, i in enumerate(org_list, 1):
			print("%s 机构名称:%s 机构地址:%s" % (code, i.org_name, i.org_address))
		num = input("选择学校:").strip()
		return org_list[int(num) - 1]

	# 选择学校课程
	@classmethod
	def select_school_class(cls, org_name=None):
		school_class_list = get_school_class_list(org_name, "school_class.pkl")
		print("%s共有%s门课程" % (org_name, len(school_class_list)))
		for code, i in enumerate(school_class_list, 1):
			print("%s 课程名称:%s 课程周期:%s课时 课程价格:%s元" % (code, i.cla_name, i.cla_time, i.cla_price))
		num = input("选择课程:").strip()
		return school_class_list[int(num) - 1]

	# 创建机构
	def create_org(self, last_dic=None):
		print("创建机构")
		org_name = input("输入机构名称:")
		address = []
		set_city(get_province(), address)
		print("-".join(address))
		school = School(org_name, "-".join(address), self.user_name)
		create_obj(school, "org_list.pkl")
		select_func(self.my_view, last_dic, self)

	# 创建讲师
	def create_teacher(self, last_dic=None):
		print("创建讲师")
		user = UserUtils.register(role=TeacherRole, admin_name=self.user_name)
		# 选择机构
		user.org_name = self.select_org(self.user_name).org_name
		create_obj(user, "teachers.pkl")
		select_func(self.my_view, last_dic, self)

	# 创建课程
	def create_class(self, last_dic=None):
		print("创建课程")
		cla_name = input("输入课程名称:")
		cla_time = input("输入课程周期:")
		cla_price = input("输入课程价格:")
		school_cla = SchoolClass(cla_name, cla_time, cla_price)
		# 选择机构
		school_cla.org_name = self.select_org(self.user_name).org_name
		create_obj(school_cla, "school_class.pkl")
		select_func(self.my_view, last_dic, class_name=self)

	# 显示机构
	def show_org(self, last_dic=None):
		org_list = get_org_list(self.user_name, "org_list.pkl")
		print("你总共有%s个学校" % len(org_list))
		for i in org_list:
			print("机构名称:%s 机构地址:%s" % (i.org_name, i.org_address))
		select_func(self.my_view, last_dic, self)

	# 显示老师
	def show_teacher(self, last_dic=None):
		teacher_list = get_org_list(self.user_name, "teachers.pkl")
		if teacher_list == None:
			print("目前您没有老师，请创建")
		else:
			print("你总共有%s个老师" % len(teacher_list))
			for i in teacher_list:
				print("机构名称:%s 老师名称:%s" % (i.org_name, i.user_name))

		select_func(self.my_view, last_dic, self)

	# 显示学校课程
	def show_school_class(self, last_dic=None):
		org_name = self.select_org(self.user_name).org_name

		school_class_list = get_school_class_list(org_name, "school_class.pkl")
		print("%s共有%s门课程" % (org_name, len(school_class_list)))
		for i in school_class_list:
			print("课程名称:%s 课程周期:%s课时 课程价格:%s元" % (i.cla_name, i.cla_time, i.cla_price))
		select_func(self.my_view, last_dic, self)

	my_view = {
		'0': ['退出', None],
		'1': ['创建机构', create_org],
		'2': ['创建讲师', create_teacher],
		'3': ['创建课程', create_class],
		'4': ['显示机构', show_org],
		'5': ['显示老师', show_teacher],
		'6': ['显示课程', show_school_class],
	}


class TeacherRole(CreateRole):
	"""
	讲师类
	"""

	def __init__(self, user_name, user_password):
		self.user_name = user_name
		self.user_password = user_password
		self.role_name = ROLE_TUPLE[2]

	def lesson_manager(self,last_dic=None):
		print("查看教授课程")
		print(self.__dict__)
		select_func(self.my_view, last_dic, self)

	def select_class(self,last_dic=None):
		print("选择教授课程")
		org_name = AdminRole.select_org(self.admin_name).org_name
		school_cls = AdminRole.select_school_class(org_name)
		school_cls.add_teacher(self)
		create_obj(school_cls, "school_class.pkl")
		my_data = get_org_list(self.admin_name,"teachers.pkl")
		for item in my_data:
			print(item.user_name)
		select_func(self.my_view, last_dic, self)




	def student_list(self,last_dic=None):
		print("查看课程下学生")

	def student_result(self,last_dic=None):
		print("修改学生分数")

	my_view = {
		'0': ['退出', None],
		'1': ['查看教授课程', lesson_manager],
		'2': ['选择教授课程', select_class],
		'3': ['查看课程下学生', student_list],
		'4': ['修改学生分数', student_result],
	}


class StudentRole(CreateRole):
	"""
	学员类
	"""

	def __init__(self, user_name, user_password):
		self.user_name = user_name
		self.user_password = user_password
		self.role_name = ROLE_TUPLE[1]

	def select_school(self):
		print("选择校区")
		org_name = AdminRole.select_org().org_name
		print(org_name)

	def select_class(self):
		print("选择课程")
		org_name = AdminRole.select_org().org_name
		cla_name = AdminRole.select_school_class(org_name).cla_name
		print(cla_name)

	def select_class(self):
		print("查看分数")

	my_view = {
		'0': ['退出', None],
		'1': ['选择校区', select_class],
		'2': ['选择课程', select_class],
		'3': ['查看分数', select_class],
	}


class UserUtils:
	"""
	用户类
	"""

	@classmethod
	def logon(cls):
		user_name = input("请输入姓名:")
		user_password = input("请输入密码:")
		m = hashlib.md5(user_password.encode('utf-8'))
		m.update(user_password.encode('utf-8'))
		return get_user(user_name, m.hexdigest())

	@classmethod
	def register(cls, role, admin_name=None):
		user_name = input("请输入姓名:")
		user_password = input("请输入密码:")
		user_pass1 = input("请再次输入用户密码进行确认:")
		if user_password != user_pass1:
			print("两次密码输入不正确")
			cls.register(role)

		m = hashlib.md5(user_password.encode('utf-8'))
		m.update(user_password.encode('utf-8'))
		# 创建用户对象
		user = role(user_name, m.hexdigest())
		if admin_name != None:
			user.admin_name = admin_name
		create_obj(user, "user.pkl")
		return user
